package com.tianji.remark.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author hc
 * @since 2024-08-26
 */
@Slf4j
//@Service
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     *  添加或取消点赞
     * @param likeRecordFormDTO 点赞数据
     */
    @Override
    public void addOrCancelLiked(LikeRecordFormDTO likeRecordFormDTO) {
        //1、判断传参是否为空
        if(!ObjectUtil.isAllNotEmpty(likeRecordFormDTO)){
            log.error("点赞数据传参异常，数据为：{}",likeRecordFormDTO);
            return;
        }

        //2、判断是否是点赞
        boolean isSuccess = likeRecordFormDTO.getLiked() ? liked(likeRecordFormDTO):unliked(likeRecordFormDTO);

        //3、统计点赞数
        if(!isSuccess){
            log.error("新增或者删除异常，数据为：{}",likeRecordFormDTO);
            return;
        }
        Integer count = lambdaQuery().eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()).count();

        //4、通过mq发消息通知业务方
        rabbitTemplate.convertAndSend(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,likeRecordFormDTO.getBizType()),
                new LikedTimesDTO(likeRecordFormDTO.getBizId(),count));
    }

    /**
     * 查询当前用户是否点赞了指定的业务
     *
     * @param bizIds 业务id
     * @return 当前用户点赞过的业务id
     */
    @Override
    public List<Long> queryIsLikedBizIds(List<Long> bizIds) {
        //1、判断传参数据是否为空
        if(ObjectUtil.isEmpty(bizIds)){
            log.error("点赞bizId传参异常，数据为：{}",bizIds);
            return Collections.EMPTY_LIST;
        }

        //2、查询当前用户是否点赞了指定的业务
        List<LikedRecord> list = lambdaQuery()
                .in(LikedRecord::getBizId, bizIds)
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .list();

        //3、返回结果

        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toList());
    }

    /**
     * 将点赞次数通知到业务方
     *
     * @param s          业务类型
     * @param maxBizSize 最大处理任务数
     */
    @Override
    public void readLikedTimesAndSendMessage(String s, int maxBizSize) {

    }

    //点赞业务
    private boolean liked(LikeRecordFormDTO likeRecordFormDTO) {
        //1、是否已经有点赞记录
        LikedRecord likedRecord = lambdaQuery()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
                .eq(LikedRecord::getBizType, likeRecordFormDTO.getBizType())
                .one();

        if(ObjectUtil.isNotEmpty(likedRecord)){
            log.error("点赞记录已存在,点赞记录为：{}",likedRecord);
            return false;
        }

        //2、未点过赞，进行新增点赞记录
        LikedRecord liked = new LikedRecord()
                .setUserId(UserContext.getUser())
                .setBizId(likeRecordFormDTO.getBizId())
                .setBizType(likeRecordFormDTO.getBizType());

        return this.save(liked);
    }

    //取消点赞业务
    private boolean unliked(LikeRecordFormDTO likeRecordFormDTO) {
        //1、直接删除

        return this.remove(new LambdaQueryWrapper<LikedRecord>()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId()));
    }
}
